#ifndef _AUDIOENGINE_H_
#define _AUDIOENGINE_H_

#include "portaudio.h"
#include "speex.h"
#include <qwidget.h>
#include <QObject>

#define SAMPLE_RATE  16000
#define FRAMES_PER_BUFFER 320
#define PA_SAMPLE_TYPE  paInt16
typedef short SAMPLE;
#define SAMPLE_SILENCE  (0)
#define NUM_CHANNELS    1
class AudioEngine;
typedef struct
{
    SanSpeexEnc     speexenc;
    SAMPLE          recordbuffer[FRAMES_PER_BUFFER * NUM_CHANNELS];
    char            encodedBufPlus8[FRAMES_PER_BUFFER * NUM_CHANNELS * 2 ];
    SanSpeexDec     speexdec;
    SAMPLE          playbackbuffer[FRAMES_PER_BUFFER * NUM_CHANNELS];
    AudioEngine    *obj;
} paTestData;

class AudioEngine : public QObject
{
    Q_OBJECT
public:
    AudioEngine();
    virtual ~AudioEngine();

    bool startPaRecorder();
    bool startPaPlayback();
    bool stopPaRecorder();
    bool stopPaPlayback();

    void recvPlaybackDataIn(QByteArray* ba);

protected:
    virtual void closeEvent(QCloseEvent *);

public slots:
    void recv_data(QByteArray* ba);

signals:
    void senddata(QByteArray*);

private:
    static int s_recordCallback(const void *inputBuffer, void *outputBuffer,
                                unsigned long framesPerBuffer,
                                const PaStreamCallbackTimeInfo* timeInfo,
                                PaStreamCallbackFlags statusFlags,
                                void *userData);
    static int s_playCallback(const void *inputBuffer, void *outputBuffer,
                              unsigned long framesPerBuffer,
                              const PaStreamCallbackTimeInfo* timeInfo,
                              PaStreamCallbackFlags statusFlags,
                              void *userData);

    bool initPa();
    bool unInitPa();

    void sendRecordDataOut(char *buf, int len);

private:

    PaStream          *m_streamIn, *m_streamOut;
    PaError            m_errIn, m_errOut;
    int                m_inputId, m_outputId;
    PaStreamParameters m_inputParameters, m_outputParameters;

    paTestData         m_data;

};

#endif // _AUDIOENGINE_H_
